package cn.flkj.gmca.ca.gmca.gmcautil;

import cn.flkj.gmca.ca.sm4.SM4Helper;
import cn.flkj.gmca.ca.sm4.SM4ModeAndPaddingEnum;
import cn.flkj.gmca.ca.sm4.SM4Util;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.encoders.Hex;

/**
 * 证书和私钥Base64的组合类,X509v3Certificate
 *
 * @author : 州长在手 2020/12/15 上午9:48
 */
public class CertAndPriKey {
    public static String certBegin = "-----BEGIN CERTIFICATE-----\n";
    public static String certEnd = "\n-----END CERTIFICATE-----";
    public static String priKeyBegin = "-----BEGIN PRIVATE KEY-----\n";
    public static String priKeyEnd = "\n-----END PRIVATE KEY-----";
    private final String base64Cert;
    private final String base64PriKey;
    private final String base64CertWithHead;
    private final String base64PriKeyWithHead;


    /**
     * 使用未Base64编码的原始密钥构造函数
     * @param priKey 私钥
     * @param cert 证书
     */
    public CertAndPriKey(byte[] priKey, byte[] cert) {
        this.base64Cert = Base64.toBase64String(cert);
        this.base64PriKey = Base64.toBase64String(priKey);
        this.base64CertWithHead = certBegin + this.base64Cert + certEnd;
        this.base64PriKeyWithHead = priKeyBegin + this.base64PriKey + priKeyEnd;
    }
    /**
     * 使用Base64编码的密钥构造函数
     * @param base64PriKey 私钥
     * @param base64Cert 证书
     */
    public CertAndPriKey(String base64PriKey, String base64Cert) {
        this.base64Cert = base64Cert;
        this.base64PriKey = base64PriKey;
        this.base64CertWithHead = certBegin + this.base64Cert + certEnd;
        this.base64PriKeyWithHead = priKeyBegin + this.base64PriKey + priKeyEnd;
    }

    public String sM4EcBase64PriKey(String keyHex) throws Exception {
        // 字符串需要HEX解码到byte数组
        return Base64.toBase64String(SM4Util.encrypt_ECB_Padding(Hex.decode(keyHex), Hex.encode(Base64.decode(this.getBase64PriKey()))));
    }
    public static String sM4EcBase64PriKey(String keyHex, String base64PriKey) throws Exception{
        // 字符串需要HEX解码到byte数组
        return Base64.toBase64String(SM4Util.encrypt_ECB_Padding(Hex.decode(keyHex), Hex.encode(Base64.decode(base64PriKey))));
    }

    public static String sM4DcBase64PriKey(String keyHex , String sM4EcBase64PriKey) throws Exception {
        // 切记SM4解密的数据要Hex decode
        return  Base64.toBase64String(Hex.decode(SM4Util.decrypt_ECB_Padding(Hex.decode(keyHex), Base64.decode(sM4EcBase64PriKey))));
    }
    public String getBase64Cert() {
        return base64Cert;
    }

    public String getBase64PriKey() {
        return base64PriKey;
    }

    public String getBase64CertWithHead() {
        return base64CertWithHead;
    }

    public String getBase64PriKeyWithHead() {
        return base64PriKeyWithHead;
    }
}
